package com.dhcc.core.framework.exception;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.ModelAndView;
/**
 * 自定义错误页面
 * @ClassName: GlobalErrorController 
 * @Description: Whitelabel Error Page处理方式
 * @author: cyf
 * @date: 2018年1月26日 上午9:33:53
 */
@Controller
public class GlobalErrorController implements ErrorController {

    private static final Logger logger = LoggerFactory.getLogger(GlobalErrorController.class);

    /**
     * Error Attributes in the Application
     */
    @Autowired
    private ErrorAttributes errorAttributes;

    private final static String ERROR_PATH = "/error";

    /**
     * Supports the HTML Error View
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = ERROR_PATH, produces = "text/html")
    public ModelAndView errorHtml(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("/error.html", getErrorAttributes(request, false));
        boolean isCustom = request.getAttribute("isCustom")!=null?(boolean) request.getAttribute("isCustom"):false;
        if(isCustom){
            view.addObject("status", request.getAttribute("status"));
            view.addObject("error", request.getAttribute("error"));
            view.addObject("message", request.getAttribute("message"));
        }
        return view;
    }

    /**
     * Supports other formats like JSON, XML
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, getTraceParameter(request));
        HttpStatus status = getStatus(request);
        boolean isCustom = request.getAttribute("isCustom")!=null?(boolean) request.getAttribute("isCustom"):false;
        if(isCustom){
            status =  HttpStatus.valueOf((Integer) request.getAttribute("status"));
            body.put("status", request.getAttribute("status"));
            body.put("error", request.getAttribute("error"));
            body.put("message", request.getAttribute("message"));
        }
        return new ResponseEntity<Map<String, Object>>(body, status);
    }

    /**
     * Returns the path of the error page.
     *
     * @return the error path
     */
    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    private boolean getTraceParameter(HttpServletRequest request) {
        String parameter = request.getParameter("trace");
        if (parameter == null) {
            return false;
        }
        return !"false".equals(parameter.toLowerCase());
    }

    private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        ServletWebRequest servletWebRequest = new ServletWebRequest(request);
        Map<String, Object> map = this.errorAttributes.getErrorAttributes(servletWebRequest, includeStackTrace);
        logger.debug("GlobalErrorController.method [error info]: status-" + map.get("status") + ", request url-" + request.getRequestURL().toString());
        return map;
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode != null) {
            try {
                return HttpStatus.valueOf(statusCode);
            } catch (Exception ex) {
            }
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }

}